package homegroup.inc.servlets;

import homegroup.inc.dao.BookDAO;
import homegroup.inc.dto.Book;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;

/**
 * Created by stone on 27.11.2014.
 */
@WebServlet(urlPatterns = {"/image/*"})
public class ImageDownloader extends HttpServlet {
    @EJB
    BookDAO bookDAO;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Book book = bookDAO.findByISBN(req.getParameter("isbn"));
        String requestedImage = req.getPathInfo();
        File image = new File(book.getCoverPath(), URLDecoder.decode(requestedImage, "UTF-8"));
        String contentType = getServletContext().getMimeType(image.getName());
        resp.reset();
        resp.setContentType(contentType);

//        resp.setContentType("image/" + getTypeOfImage(book));
//        InputStream inputStream = new FileInputStream(new File(book.getCoverPath()));
//        OutputStream outputStream = resp.getOutputStream();
//        int read;
//        byte[] readBytes = new byte[1024];
//        while ((read = inputStream.read()) != -1) {
//            outputStream.write(readBytes, 0, read);
//        }
//
    }
//    private String getTypeOfImage(Book book) {
//        String coverPath = book.getCoverPath();
//        String extension = coverPath.substring(coverPath.lastIndexOf("\\.") + 1);
//        return extension;
//    }

//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        Book book = bookDAO.findByISBN(req.getParameter("path"));
//        InputStream inputStream = new FileInputStream(new File(book.getCoverPath()));
//        OutputStream outputStream = resp.getOutputStream();
//        int read;
//        byte[] readBytes = new byte[1024];
//        while ((read = inputStream.read()) != -1) {
//            outputStream.write(readBytes, 0, read);
//        }
//    }
}
